﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WordFun.Models;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace WordFun.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class WordsManagement : Common.LayoutAwarePage
    {
        private List<Word> _allWords;
        private List<Word> _searchResult;

        private bool _isAddNew = false;

        public WordsManagement()
        {
            this.InitializeComponent();

            _allWords = new List<Word>();
            _allWords = DataSource.GetAllWords();
            listWords.ItemsSource = _allWords;

            UnenableToEdit();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        public void EnableToAddNew()
        {
            txtID.Text = "";
            txtID.IsReadOnly = false;
            txtContent.IsReadOnly = false;
            txtContent.Text = "";
            txtMeaning.IsReadOnly = false;
            txtMeaning.Text = "";

            rdCantEdit.IsEnabled = true;
            rdCantEdit.IsChecked = false;
            rdCanEdit.IsEnabled = true;
            rdCanEdit.IsChecked = false;

            btnNew.IsEnabled = true;
            btnEdit.IsEnabled = false;
            btnSave.IsEnabled = true;
            btnRemove.IsEnabled = false;
        }

        public void UnenableToAddNew()
        {
            txtID.Text = "";
            txtID.IsReadOnly = true;
            txtContent.IsReadOnly = true;
            txtContent.Text = "";
            txtMeaning.IsReadOnly = true;
            txtMeaning.Text = "";

            rdCantEdit.IsEnabled = false;
            rdCantEdit.IsChecked = false;
            rdCanEdit.IsEnabled = false;
            rdCanEdit.IsChecked = false;

            btnNew.IsEnabled = true;
            btnEdit.IsEnabled = false;
            btnSave.IsEnabled = false;
            btnRemove.IsEnabled = false;
        }

        public void EnableToEdit()
        {
            rdCanEdit.IsChecked = true;
            rdCantEdit.IsEnabled = true;
            rdCanEdit.IsEnabled = true;

            txtID.IsReadOnly = true;
            txtContent.IsReadOnly = false;
            txtMeaning.IsReadOnly = false;

            btnEdit.IsEnabled = true;
            btnRemove.IsEnabled = true;
            btnSave.IsEnabled = true;
        }

        public void UnenableToEdit()
        {
            rdCantEdit.IsEnabled = false;
            rdCanEdit.IsEnabled = false;

            txtID.IsReadOnly = true;
            txtContent.IsReadOnly = true;
            txtMeaning.IsReadOnly = true;

            btnEdit.IsEnabled = false;
            btnSave.IsEnabled = false;
            btnRemove.IsEnabled = false;
        }

        private void txtSearch_GotFocus(object sender, RoutedEventArgs e)
        {
            txtSearchQuerry.Text = "";
            txtSearchQuerry.Foreground = new SolidColorBrush(Colors.Black);
        }

        private void txtSearchQuerry_LostFocus(object sender, RoutedEventArgs e)
        {
            txtSearchQuerry.Text = "Type here...";
            txtSearchQuerry.Foreground = new SolidColorBrush(Colors.Gray);
        }

        private void txtSearchQuerry_TextChanged(object sender, TextChangedEventArgs e)
        {
            string querry = txtSearchQuerry.Text;

            if (!string.IsNullOrEmpty(querry))
            {
                if (!querry.Contains("Type here"))
                {
                    _searchResult = new List<Word>();
                    _searchResult = DataSource.GetWordsByContent(querry);
                    listWords.ItemsSource = _searchResult;
                }
            }
            else
                listWords.ItemsSource = _allWords;
            listWords.UpdateLayout();
        }

        private void listWords_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Word word = listWords.SelectedItem as Word;

            if (word == null)
            {
                EnableToAddNew();

                return;
            }
            txtID.Text = word.Id.ToString();
            txtContent.Text = word.Content;
            txtMeaning.Text = word.Meaning;
            UnenableToEdit();
            if (word.CanEdit != 0)
            {
                btnEdit.IsEnabled = true;
                btnRemove.IsEnabled = true;
                rdCanEdit.IsChecked = true;
                rdCantEdit.IsChecked = false;
            }
            else
            {
                rdCantEdit.IsChecked = true;
            }
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            _isAddNew = true;
            listWords.SelectedItem = null;

            EnableToAddNew();
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            EnableToEdit();
        }

        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            int id = int.Parse(txtID.Text);
            string content = txtContent.Text;
            string meaning = txtMeaning.Text;
            int canEdit = 1;
            if (rdCantEdit.IsChecked == true)
                canEdit = 0;

            int result = 0;

            if (!_isAddNew)
                DataSource.EditWord(id, content, meaning, canEdit);
            else
            {
                result = DataSource.AddWord(id, content, meaning, canEdit);
                if (result == 0)
                {
                    MessageDialog msg = new MessageDialog(string.Format(@"The word with Id ""{0}"" is already exists. Please type another word...", id));
                    msg.Title = "Word Fun";
                    await msg.ShowAsync();
                }
                else
                {
                    _allWords = DataSource.GetAllWords();
                    listWords.ItemsSource = _allWords;
                    UnenableToEdit();
                }
            }
        }

        private async void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            int id = int.Parse(txtID.Text);
            DataSource.RemoveWord(id);
            _allWords = DataSource.GetAllWords();
            listWords.ItemsSource = _allWords;

            MessageDialog msg = new MessageDialog("Removed");
            msg.Title = "Word Fun";
            await msg.ShowAsync();
        }

        private async void btnGame1_Click(object sender, RoutedEventArgs e)
        {
            var item = listWords.SelectedItem as Word;
            if (item == null)
            {
                MessageDialog msg = new MessageDialog("Please select a word to play game");
                msg.Title = "Word Fun";
                await msg.ShowAsync();
            }
            else
            {
                Views.SceneSwapGame._content = item.Content;
                this.Frame.Navigate(typeof(Views.SceneSwapGame));
            }
        }
    }
}
